package org.geometerplus.zlibrary.core.filesystem.ceb;

import org.geometerplus.zlibrary.core.filesystem.ZLArchiveEntryFile;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


public final class LQCebEntryFile extends ZLArchiveEntryFile {
    public	static List<ZLFile> archiveEntries(ZLFile archive) {
		try {
			final CebFile cebf = LQCebEntryFile.geCebFile(archive);
			cebf.getAllSubFiles( );
		} catch (IOException e) {
		}
		return Collections.emptyList();
	}

	private static HashMap<ZLFile,CebFile> ourCebFileMap = new HashMap<ZLFile,CebFile>();

	private static CebFile geCebFile(final ZLFile file) throws IOException {
		synchronized (ourCebFileMap) {
			CebFile cebf = file.isCached() ? ourCebFileMap.get(file) : null;
			if (cebf == null) {
				cebf = new CebFile(file);
				cebf.DecompressCEBFile();
				if (file.isCached()) {
					ourCebFileMap.put(file, cebf);
				}
			}
			return cebf;
		}
	}

	static void removeFromCache(ZLFile file) {
		ourCebFileMap.remove(file);
	}

	public LQCebEntryFile(ZLFile parent, String name) {
		super(parent, name);
	}

	@Override
	public boolean exists() {
		try {
			return myParent.exists() && geCebFile(myParent).subFileExists(myName);
		} catch (IOException e) {
			return false;
		}
	}

	@Override
	public long size() {
		try {
			return geCebFile(myParent).getSubFileSize(myName);
		} catch (IOException e) {
			return 0;
		}
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return geCebFile(myParent).getSubFileInputStream(myName);
	}
}
